package com.lyuewei.ringtone.viewmodel; // 替换为你的 ViewModel 包名

import android.app.Application;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import com.lyuewei.ringtone.MyApplication; // 导入你的 Application 类
import com.lyuewei.ringtone.data.AppDatabase;
import com.lyuewei.ringtone.data.RingerSetting;
import com.lyuewei.ringtone.data.RingerSettingDao;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SettingsViewModel extends AndroidViewModel {

    private RingerSettingDao ringerSettingDao;
    private LiveData<List<RingerSetting>> allSettings;

    // 使用 ExecutorService 在后台线程执行数据库操作
    private final ExecutorService databaseWriteExecutor =
            Executors.newSingleThreadExecutor();

    public SettingsViewModel(Application application) {
        super(application);

    }
    public void init() {
        AppDatabase db = MyApplication.getDatabase();
        ringerSettingDao = db.ringerSettingDao();
        allSettings = ringerSettingDao.getAllSettings();
    }

    // 插入设置
    public void insert(RingerSetting setting) {
        databaseWriteExecutor.execute(() -> {
            ringerSettingDao.insert(setting);
        });
    }

    // 更新设置
    public void update(RingerSetting setting) {
        databaseWriteExecutor.execute(() -> {
            ringerSettingDao.update(setting);
        });
    }

    // 删除设置
    public void delete(RingerSetting setting) {
        databaseWriteExecutor.execute(() -> {
            ringerSettingDao.delete(setting);
        });
    }

    // 获取所有设置的 LiveData
    public LiveData<List<RingerSetting>> getAllSettings() {
        return allSettings;
    }

}